package com.cc.controller;

import com.cc.dto.ProductDTO;
import com.cc.entity.Products;
import com.cc.service.ProductsService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/api/products")
public class ProductController {

    @Autowired
    private ProductsService productsService;

    // 添加商品
    @PostMapping
    public String addProduct(@RequestBody ProductDTO productDTO) {
        Products product = new Products();
        BeanUtils.copyProperties(productDTO, product);
        int result = productsService.addProduct(product);
        return result > 0 ? "商品添加成功" : "商品添加失败";
    }

    // 删除商品
    @DeleteMapping("/{id}")
    public String deleteProduct(@PathVariable Integer id) {
        int result = productsService.deleteProduct(id);
        return result > 0 ? "商品删除成功" : "商品删除失败";
    }

    // 更新商品
    @PutMapping
    public String updateProduct(@RequestBody ProductDTO productDTO) {
        Products product = new Products();
        BeanUtils.copyProperties(productDTO, product);
        int result = productsService.updateProduct(product);
        return result > 0 ? "商品更新成功" : "商品更新失败";
    }

    // 获取所有商品
    @GetMapping
    public List<ProductDTO> getAllProducts() {
        List<Products> products = productsService.getAllProducts();
        return products.stream().map(product -> {
            ProductDTO dto = new ProductDTO();
            BeanUtils.copyProperties(product, dto);
            dto.setStatus(product.getStatus().toString());
            return dto;
        }).collect(Collectors.toList());
    }
}
